package com.xiaoma.server;

import com.xiaoma.entity.RpcRequest;
import com.xiaoma.entity.RpcResponse;
import com.xiaoma.registry.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @Author: xiaoma
 * @Date: 2021/7/5 15:05
 * @description: 实际处理RpcRequest的工作线程
 */
public class RequestHandlerThread implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(RequestHandlerThread.class);

    private Socket socket;
    private RequestHandler requestHandler;

    public RequestHandlerThread(Socket socket, RequestHandler requestHandler) {
        this.socket = socket;
        this.requestHandler = requestHandler;
    }

    @Override
    public void run() {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
            //接受RpcRequest对象
            RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
            //调用requestHandler处理后返回结果
            Object result = requestHandler.handle(rpcRequest);
            //生成RpcResponse对象传输回去
            objectOutputStream.writeObject(RpcResponse.success(result));

            objectOutputStream.flush();
        } catch (IOException | ClassNotFoundException e) {
            logger.error("调用或发送时有错误发生：", e);
        }
    }

}
